
(in-package #:smugmug)

(defvar *smugmug-upload-url* (puri:parse-uri "http://upload.smugmug.com/photos/xmladd.mg"))

(defmethod upload (pathname album &optional caption (upload-url *smugmug-upload-url*))
  (flet ((get-file-byte-count (pathname)
           (with-open-file (stream pathname :direction :input :element-type '(unsigned-byte 8))
             (file-length stream))))
    (let ((parameters `(("ByteCount" . ,(format nil "~D" (get-file-byte-count pathname)))
                        ("MD5Sum" . ,(ironclad:byte-array-to-hex-string (ironclad:digest-file :md5 pathname)))
                        ("AlbumID" . ,(format nil "~D" (album-id album)))
                        ("ResponseType" . "REST")
                        ("SessionID" . ,(session-id (session album)))
                        ("file" . ,pathname))))
      (when caption
        (push `("Caption" . ,caption) parameters))
      (let ((response (rest-request :session (session album)
                                    :parameters parameters
                                    :rest-url upload-url)))
        (make-instance 'image
                       :image-id (dom:data (elt (dom:child-nodes (elt (dom:get-elements-by-tag-name response "ImageID") 0)) 0)))))))

;;; TODO implement smugmug.images.uploadFromURL
